import os
import random
from .config import get_option

_g_music_list = None

def get_music_dir():
    return os.path.expanduser(get_option("music_dirs", "~/Music"))

def refresh_music_list():
    global _g_music_list
    _g_music_list = None

def get_music_list():
    global _g_music_list
    if _g_music_list is not None:
        return _g_music_list
    musics = []
    musicdir = get_music_dir()
    for path in os.listdir(musicdir):
        if path.endswith('.mp4') or path.endswith('.mp3'):
            name = path[:-4]
            if name.startswith('bilibili-'):
                name = name[9:]
            musics.append({"name": name, "path": os.path.join(musicdir, path)})
    rng = random.Random(4399)
    rng.shuffle(musics)
    _g_music_list = musics
    return musics
